<template>
    <view class="xilu">
        <view class="page-foot bg-white" @click="formSubmit()">
            <view class="btn1">立即发布</view>
        </view>
        <view class="container plr30 pt30">
            <view class="flex-box flex-between pb30">
                <view class="fs34 fwb">分类</view>
                <!-- <view class="fs24 col89">更多+</view> -->
            </view>

            <multi-select :items="categoryList" @change="bindCategoryChange" id_key="id" name_key="name" children_key="childlist" :value="product.category_id" ref="pickers">
                <view class="area flex-box m-arrow-right">
					<view>分类</view>
                    <view class="fs30 cola flex-grow-1 tr" v-if="!selectedSecond">请选择</view>
                    <view class="fs30 cola flex-grow-1 tr" v-else> {{selectedFirst.name}} -
                        {{selectedSecond.name}}
                    </view>
                </view>
            </multi-select>
            <view class="ptb30 fs34 fwb">区域</view>
            <multi-select :items="areas" @change="bindDistrictChange" id_key="id" name_key="name" children_key="childlist" :value="product.region_id" ref="pickers">
                <view class="area flex-box m-arrow-right">
                    <view>省市区</view>
                    <view class="fs30 cola flex-grow-1 tr" v-if="!selectedDistrict">请选择</view>
					<view class="fs30 cola flex-grow-1 tr" v-else>{{selectedCity.name}} - {{selectedDistrict.name}}</view>
                </view>
            </multi-select>
            <view class="ptb30 fs30 col5">详细地址</view>
            <textarea class="xilu_text3 fs30" v-model="product.address" maxlength="600" placeholder="请输入详细地址" placeholder-class="colc"></textarea>
            <view class="ptb30 fs34 fwb">图片</view>
            <u-upload :fileList="fileListimages" @afterRead="afterRead" @delete="deletePic" name="images" multiple :maxCount="10" width="210" height="210" :previewFullImage="true"></u-upload>
            <view class="ptb30 fs34 fwb">商品标题</view>
            <textarea class="xilu_text1 fs30" v-model="product.name" maxlength="50" placeholder="请输入商品标题" placeholder-class="colc"></textarea>
            <view class="ptb30 fs34 fwb">商品描述</view>
            <textarea class="xilu_text2 fs30" v-model="product.content" maxlength="600" placeholder="请输入商品描述" placeholder-class="colc"></textarea>
            <view class="flex-box pt30 pb50">
                <view class="flex-grow-1 fs34 fwb">商品价格</view>
                <view class="fs34 cola">¥</view>
                <input type="number" placeholder-class="cola" v-model="product.salesprice" class="fs34 xilu_input" placeholder="请输入">
            </view>
            <view class="flex-box pt30 pb50">
                <view class="flex-grow-1 fs34 fwb">商品原价</view>
                <view class="fs34 cola">¥</view>
                <input type="number" placeholder-class="cola" v-model="product.line_price" class="fs34 xilu_input" placeholder="请输入">
            </view>
            <picker @change="chooseAction" :value="actionIndex" :range="action" range-key="name">
                <view class="flex-box m-arrow-right mb30">
                    <view class="flex-grow-1 fs34 fwb">发货方式</view>
                    <view class="fs34" :class="actionIndex===''?'cola':'col5'">{{actionIndex===''?'请选择':action[actionIndex].name}}
                    </view>
                </view>
            </picker>
            <view class="flex-box pt30 pb50" v-if="actionIndex !== '' && action[actionIndex].id==1">
                <view class="flex-grow-1 fs34">运费</view>
                <view class="fs34 cola">¥</view>
                <input type="number" placeholder-class="cola" v-model="product.freight_money" class="fs34 xilu_input" placeholder="请输入">
            </view>
        </view>

    </view>
</template>

<script>
    import multiSelect from '@/components/multi-select/multi-select.vue';
    var validate = require("../../xilu/validate.js");
    export default {
        components: {
            multiSelect
        },
        data() {
            return {
                fileListimages: [],
                action: [{
                    id: 1,
                    name: '需要运费'
                }, {
                    id: 2,
                    name: '包邮'
                }, {
                    id: 3,
                    name: '自提'
                }],
                actionIndex: "",
                pickerPop: false,
                product: {
                    product_type: 1,
                    category_id: '',
					province_id: 0,
					city_id: 0,
					region_id: 0,
					address:'',
                    name: '',
                    content: '',
                    salesprice: '',
                    line_price: ''
                },
                categoryList: [],
                selectedFirst: null,
                selectedSecond: null,
                areas: [],
				selectedProvince: null,
				selectedCity: null,
				selectedDistrict: null,
            };
        },
        onLoad() {
            let page = this;
            this.getOpenerEventChannel().on('addProductTransfor', function(product) {
                if (Object.keys(product).length > 0) {
                    page.product = product;
                    let images = [];
                    product.images.forEach(item => {
                        images.push({
                            status: 'success',
                            message: '',
                            url: item
                        })
                    })
                    page.fileListimages = images;
                    page.actionIndex = product.freight_status - 1;
                }
            })
            page.fetchCategoryList();
            this.$util.getAreaTree(false).then(areas=>{
				page.areas = areas;
			})
        },
        methods: {
            bindPickerChange: function(e) {
                console.log('picker发送选择改变，携带值为', e.detail.value)
                this.index = e.detail.value
            },
            //分类
            fetchCategoryList() {
                this.$core.get({
                    url: 'xilumarket.product_category/lists',
                    data: {},
                    loading: false,
                    success: ret => {
                        this.categoryList = ret.data;
                    }
                })
            },
            //分类
            bindCategoryChange(e) {
                let categoryIndex = e.indexValues;
                let categoryList = this.categoryList;
                this.product.category_id = categoryList[categoryIndex[0]].childlist[categoryIndex[1]].id;
                this.selectedFirst = {
                    id: categoryList[categoryIndex[0]].id,
                    'name': categoryList[categoryIndex[0]].name
                };
                this.selectedSecond = {
                    id: categoryList[categoryIndex[0]].childlist[categoryIndex[1]].id,
                    'name': categoryList[categoryIndex[0]].childlist[categoryIndex[1]].name
                };
            },
			bindDistrictChange(e) {
				let areaIndex = e.indexValues;
				let areas = this.areas;
				this.product.province_id = areas[areaIndex[0]].id;
				this.product.city_id = areas[areaIndex[0]].childlist[areaIndex[1]].id;
				this.product.region_id = areas[areaIndex[0]].childlist[areaIndex[1]].childlist[areaIndex[2]].id;
				this.selectedProvince = {
					id: areas[areaIndex[0]].id,
					'name': areas[areaIndex[0]].name
				};
				this.selectedCity = {
					id: areas[areaIndex[0]].childlist[areaIndex[1]].id,
					'name': areas[areaIndex[0]].childlist[areaIndex[1]].name
				};
				this.selectedDistrict = {
					id: areas[areaIndex[0]].childlist[areaIndex[1]].childlist[areaIndex[2]].id,
					'name': areas[areaIndex[0]].childlist[areaIndex[1]].childlist[areaIndex[2]].name
				};
			
			},
            // 确认选择
            confirm(e) {
                this.pickerPop = false;
                console.log(e.indexs[0], e.indexs[1]);
            },
            // 删除图片
            deletePic(event) {
                this[`fileList${event.name}`].splice(event.index, 1)
            },
            // 新增图片
            async afterRead(event) {
                // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
                let lists = [].concat(event.file)
                let fileListLen = this[`fileList${event.name}`].length
                lists.map((item) => {
                    this[`fileList${event.name}`].push({
                        ...item,
                        status: 'uploading',
                        message: '上传中'
                    })
                })
                for (let i = 0; i < lists.length; i++) {
                    const result = await this.uploadFilePromise(lists[i].url)
                    let item = this[`fileList${event.name}`][fileListLen]
                    this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: result
                    }))
                    fileListLen++
                }
            },
            uploadFilePromise(filepath) {
                let page = this;
                return new Promise((resolve, reject) => {
                    page.$core.uploadFile({
                        filePath: filepath,
                        success: (ret, response) => {
                            resolve(ret.data.url)
                        }
                    })
                })
            },
            //运费
            chooseAction(e) {
                this.actionIndex = e.detail.value;
            },
            //提交
            formSubmit() {
                let formData = this.product;
                if (this.actionIndex != '') {
                    formData.freight_status = this.action[this.actionIndex].id;
                }

                let images = []
                this.fileListimages.forEach(item => images.push(item.url));
                formData.images = images.join(',');
                var rule = [{
                        name: 'category_id',
                        nameChn: '分类',
                        rules: ['require', 'gt:0'],
                        errorMsg: {
                            require: '请选择商品分类',
                            gt: '请选择商品分类'
                        },
                    },
					{
					        name: 'region_id',
					        nameChn: '区域',
					        rules: ['require', 'gt:0'],
					        errorMsg: {
					            require: '请选择发布区域',
					            gt: '请选择发布区域'
					        },
					},
                    {
                        name: 'name',
                        nameChn: '商品标题',
                        rules: ['require', 'length:1,50'],
                        errorMsg: {
                            require: '请填写商品标题',
                            length: "标题限制50字"
                        },
                    },
                    {
                        name: 'content',
                        nameChn: '商品描述',
                        rules: ['require', 'length:1,600'],
                        errorMsg: {
                            require: '请填写商品描述',
                            length: "描述限制600字"
                        },
                    },
                    {
                        name: 'salesprice',
                        nameChn: '商品价格',
                        rules: ['require', 'gt:0'],
                        errorMsg: {
                            require: '请填写商品价格',
                            gt: "价格大于0"
                        },
                    },
                    {
                        name: 'freight_status',
                        nameChn: '发货方式',
                        rules: ['require', 'notIn:1,2,3'],
                        errorMsg: {
                            require: '请选择发货方式',
                            notIn: "请选择发货"
                        },
                    },
                ];
                // 是否全部通过，返回Boolean
                //console.log(validate.check(formData,rule),validate.getError(),formData);

                if (!validate.check(formData, rule)) {
                    uni.showToast({
                        title: validate.getError()[0],
                        icon: 'none'
                    });
                    return;
                }
				let page = this;
                this.$core.post({
                    url: 'xilumarket.product/add',
                    data: formData,
                    success: ret => {
                        uni.showModal({
                            title: '提示',
                            content: '发布成功，等待审核',
                            showCancel: false,
                            success(res) {
								page.getOpenerEventChannel().emit("setSuccess",{})
                                uni.navigateBack({});
                            }
                        });
                    }
                })
            }
        }
    }
</script>

<style lang="scss" scoped>
    .xilu {
        &_target {
            padding: 0 18rpx;
            height: 70rpx;
            line-height: 70rpx;
            background-color: #F7F9FC;
            border-radius: 10rpx;
            margin-right: 20rpx;
            margin-bottom: 20rpx;

            &.active {
                background-color: #FFC100;
            }
        }

        &_text1 {
            width: 690rpx;
            height: 160rpx;
            background: #F7F9FC;
            border-radius: 20rpx;
            padding: 30rpx;
        }

        &_text2 {
            width: 690rpx;
            height: 470rpx;
            background: #F7F9FC;
            border-radius: 20rpx;
            padding: 30rpx;
        }
        &_text3 {
            width: 690rpx;
            height: 200rpx;
            background: #F7F9FC;
            border-radius: 20rpx;
            padding: 30rpx;
        }

        &_input {
            width: 150rpx;
            padding-left: 30rpx;
        }

        .m-arrow-right:after {
            border-color: #aaa;
        }

        .area {
            width: 690rpx;
            height: 110rpx;
            background: #F7F9FC;
            border-radius: 20rpx;
            padding: 0 50rpx 0 30rpx;

            &::after {
                right: 30rpx;
            }
        }
    }
</style>